package rsadecrypt

import (
	"RSA/utils"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"os"
)

// 私钥解密
func Decrypt(PrivateKeyFile string, CipherFile string) (PlainTextBytes []byte, err error) {
	prikeyfile, err := os.Open(PrivateKeyFile)
	if err != nil {
		return nil, err
	}
	// 读取私钥文件内容
	prikeyfilebytes, err := ioutil.ReadAll(prikeyfile)
	if len(prikeyfilebytes) >= 0 {
		if err != nil {
			return nil, err
		}
	} else {
		return nil, fmt.Errorf("This private key file is NULL!")
	}
	// 将私钥文件转换成pem格式的对象
	prikeyblock, _ := pem.Decode(prikeyfilebytes)
	if prikeyblock == nil || prikeyblock.Type != "RSA PRIVATE KEY" {
		return nil, fmt.Errorf("failed to decode PEM block containing private key")
	}
	// 提取私钥值
	privateKey, err := x509.ParsePKCS1PrivateKey(prikeyblock.Bytes)
	if err != nil {
		return nil, err
	}
	// 获取公钥长度（明文的长度与公钥的长度相等）
	partSize := privateKey.PublicKey.N.BitLen() / 8
	cipherfile, err := os.Open(CipherFile)
	if err != nil {
		return nil, err
	}
	cipherbytes, _ := ioutil.ReadAll(cipherfile)
	chunks := utils.SplitMsg(cipherbytes, partSize)
	for _, chunk := range chunks {
		plainbytes, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, chunk)
		PlainTextBytes = append(PlainTextBytes, plainbytes[:]...)
	}
	return PlainTextBytes, nil
}
